package com.zyht.bank.manage.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.zyht.bank.entity.AxdInformationNotices;
import com.zyht.bank.entity.AxdInformationNoticesExample;
import com.zyht.bank.entity.AxdInformationNoticesExample.Criteria;
import com.zyht.bank.service.AxdInformationNoticesService;
import com.zyht.bank.service.AxdOrgInfoService;
import com.zyht.common.AbsManageBaseController;
import com.zyht.common.intercepter.Token;
import com.zyht.common.util.DateUtils;
import com.zyht.common.util.Page;
import com.zyht.common.util.RegexUtils;
import com.zyht.common.util.UploaderUtils;

@Controller
@RequestMapping(value = "admin/informationNotices")
public class AdminInformationNotices extends AbsManageBaseController {
	@Resource
	private AxdInformationNoticesService axdInformationNoticesService;
	@Resource
	private AxdOrgInfoService axdOrgInfoService;

	@Token(save = true)
	@RequestMapping(value = "/index")
	public String index(

			Integer currentPage, @RequestParam(value = "startTime", required = false) String startTime,
			@RequestParam(value = "endTime", required = false) String endTime,
			@RequestParam(value = "title", required = false) String title,
			@RequestParam(value = "status", required = false) String status, HttpServletRequest request, Model model) {
		// String wxid = PropertiesUtils.getConfig("globle_default_wxid");

		// SysUser sessionUser = getSessionUser(request);
		// AxdOrgInfo findOneById =
		// axdOrgInfoService.findOneById(sessionUser.getOrgId());
		Date startTime1 = null;
		Date endTime1 = null;
		if (null == currentPage || currentPage == 0) {
			currentPage = 1;
		}
		// 封装参数
		AxdInformationNoticesExample informationNoticesExample = new AxdInformationNoticesExample();
		Criteria criteria = informationNoticesExample.createCriteria();
		informationNoticesExample.setOrderByClause("create_time desc");
		if (StringUtils.isNotEmpty(title)) {
			criteria.andTitleLike("%" + title + "%");
			model.addAttribute("title", title);
		}
		if (StringUtils.isNotEmpty(status)) {
			criteria.andStatesEqualTo(Integer.parseInt(status));
			model.addAttribute("status", status);
		}

		/*
		 * if (StringUtils.isNotEmpty(findOneById.getOrgCode())) {
		 * criteria.andOrgCodeEqualTo(findOneById.getOrgCode());
		 * model.addAttribute("orgCode", findOneById.getOrgCode()); }
		 */

		if (StringUtils.isNotEmpty(startTime)) {
			try {
				startTime1 = DateUtils.parseDatetime(startTime);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			criteria.andCreateTimeGreaterThanOrEqualTo(startTime1);
			model.addAttribute("startTime", startTime);
		}
		if (StringUtils.isNotEmpty(endTime)) {
			try {
				endTime1 = DateUtils.parseDatetime(endTime);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			criteria.andCreateTimeLessThanOrEqualTo(endTime1);
			model.addAttribute("endTime", endTime);
		}
		int pageSize = getPageSize();
		PageHelper.startPage(currentPage, pageSize);
		com.github.pagehelper.Page<AxdInformationNotices> pageInfo = (com.github.pagehelper.Page<AxdInformationNotices>) axdInformationNoticesService
				.list(informationNoticesExample);
		int total = Long.valueOf(pageInfo.getTotal()).intValue();
		Page<AxdInformationNotices> page = new Page<AxdInformationNotices>(total, currentPage, pageSize);
		page.setRecordList(pageInfo);
		model.addAttribute("page", page);

		return "banks/manage/informationNotices/index";
	}

	@RequestMapping(value = "/add")
	public String add(Model model) {
		// String wxid = getWxid();
		return "banks/manage/informationNotices/add";
	}

	@Token(save = true)
	@RequestMapping(value = "/edit")
	public String edit(@RequestParam(value = "id", required = true) String id, HttpServletRequest request,
			Model model) {
		// 通过session来获取机构码来关联机构
		// SysUser sysUser = getSessionUser(request);
		// if (sysUser != null) {
		// AxdOrgInfo orgInfo =
		// axdOrgInfoService.findOneById(sysUser.getOrgId());
		// }
		AxdInformationNotices information = axdInformationNoticesService.findOneById(Integer.parseInt(id));
		if (information != null) {
			model.addAttribute("bean", information);
			return "banks/manage/informationNotices/edit";
		}
		model.addAttribute("msg", "您没有权限操作");
		model.addAttribute("redirect", "manage/informationNotices/index");
		return "message";
	}

	@Token(save = true)
	@RequestMapping(value = "/save")
	public String save(@RequestParam(value = "noticesId", required = false) String noticesId,
			@RequestParam(value = "title", required = true) String title,
			// @RequestParam(value="typeVal",required=true)String type,
			@RequestParam(value = "content", required = false) String content,
			@RequestParam(value = "status", required = false) String states,
			@RequestParam(value = "imgeUrl", required = false) String imgeUrl,
			@RequestParam(value = "isTop", required = false) String isTop,
			@RequestParam(value = "isNew", required = false) String isNew, HttpServletRequest request, Model model) {
		// SysUser sessionUser = getSessionUser(request);
		// AxdOrgInfo findOneById =
		// axdOrgInfoService.findOneById(sessionUser.getOrgId());
		AxdInformationNotices bean = new AxdInformationNotices();
		bean.setTitle(title);
		bean.setContent(content);
		bean.setImgeUrl(imgeUrl);
		bean.setIsTop(Integer.valueOf(isTop));
		bean.setIsNew(Integer.valueOf(isNew));
		bean.setStates(Integer.valueOf(states));
		bean.setCreateTime(DateUtils.now());
		// bean.setOrgCode(findOneById.getOrgCode());
		Integer count = 0;
		if (!StringUtils.isEmpty(noticesId)) {
			bean.setNoticesId(Integer.valueOf(noticesId));
			count = axdInformationNoticesService.updateById(bean);
		} else {
			bean.setCreateTime(DateUtils.now());
			bean.setWatchTimes(0);
			count = axdInformationNoticesService.addOne(bean);
		}
		if (null == count || count <= 0) {
			logger.debug("文章信息设置失败");
			model.addAttribute("msg", "文章信息设置失败");
			model.addAttribute("redirect", "admin/informationNotices/add");
			return "message";
		}
		model.addAttribute("msg", "文章信息设置成功");
		model.addAttribute("redirect", "admin/informationNotices/index");
		return "message";
	}

	// @RequestMapping(value="/del")
	// public String delete(HttpServletRequest request,
	// @RequestParam(value="id",required=true)String id,Model model){
	// if(!StringUtils.isEmpty(id)){
	// SbeArticle bean =
	// sbeArticleService.selectByPrimaryKey(Integer.valueOf(id));
	// int row = sbeArticleService.deleteByPrimaryKey(Integer.valueOf(id));
	// //删除图片和文件资源
	// if(row > 0){
	// try{
	// String filePath = bean.getSourceHref();
	// if(filePath.contains("path=")){
	// UploaderUtils.delete(filePath, request);
	// }
	// String logoPath = bean.getLogo();
	// if(logoPath.contains("path=")){
	// UploaderUtils.delete(logoPath, request);
	// }
	// }catch(Exception e){
	// logger.debug("删除图片和文件异常"+e.getMessage());
	// }
	// }
	// }
	// model.addAttribute("msg", "删除成功");
	// model.addAttribute("redirect", "admin/article/index");
	// return "message";
	// }
	@RequestMapping(value = "/upFile")
	public String upFile() {

		return "banks/manage/informationNotices/file_upload";
	}

	@RequestMapping(value = "uploadFile")
	public void uploadFile(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "file", required = true) MultipartFile file) {
		// String appendPath = "";
		String[] urls = null;
		try {
			urls = UploaderUtils.upload2("file", file.getInputStream(), file.getOriginalFilename(), request);
		} catch (IOException e) {
			PrintWriter pw;
			try {
				pw = response.getWriter();
				pw.write("<script type='text/javascript'>window.parent.closeFileWin(null)</script>");
				pw.flush();
			} catch (IOException e1) {
				logger.error("发生IO异常!");
			}
			return;
		}
		logger.debug("文件相对路径是:" + urls[1]);
		String webUrl = urls[1].replace("\\", "/");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter pw;
		try {
			pw = response.getWriter();
			pw.write("<script type='text/javascript'>window.parent.closeFileWin('" + webUrl + "')</script>");
			pw.flush();
		} catch (IOException e) {
			logger.error("发生IO异常!");
		}
		return;
	}

	@RequestMapping(value = "upLogo")
	public String upLogo() {

		return "banks/manage/informationNotices/img_upload";
	}

	@RequestMapping(value = "uploadImage")
	public void uploadImage(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "picture", required = true) MultipartFile picture) {
		String[] fileTypeStr = { "image/gif", "image/x-png", "image/pjpeg", "image/jpeg", "image/bmp", "image/png" };
		String type = picture.getContentType();
		for (String str : fileTypeStr) {
			if (type.indexOf(str) == -1) {
				// String appendPath = "";
				String[] urls = null;
				try {
					urls = UploaderUtils.upload2("image", picture.getInputStream(), picture.getOriginalFilename(),
							request);
				} catch (IOException e) {
					PrintWriter pw;
					try {
						pw = response.getWriter();
						pw.write("<script type='text/javascript'>window.parent.closePicWin(null)</script>");
						pw.flush();
					} catch (IOException e1) {
						logger.error("发生IO异常!");
					}
					break;
				}
				logger.debug("文件相对路径是:" + urls[1]);
				String webUrl = urls[1].replace("\\", "/");
				PrintWriter pw;
				try {
					pw = response.getWriter();
					pw.write("<script type='text/javascript'>window.parent.closePicWin('" + webUrl + "')</script>");
					pw.flush();
				} catch (IOException e) {
					logger.error("发生IO异常!");
				}
				break;
			}
		}
	}

	/*		*//**
				 * @Description
				 * @author Steven
				 * @param id
				 * @param response
				 * @return
				 */
	/*
	 * @RequestMapping("download") public String
	 * download(@RequestParam(value="id",required=true)String id,
	 * HttpServletResponse response){ if(RegexUtils.isNumber(id)){ SbeArticle
	 * bean = sbeArticleService.selectByPrimaryKey(Integer.valueOf(id)); if(null
	 * != bean){ try { InputStream is =
	 * StaticFileSysUtils.fetchStream(bean.getSourceHref());
	 * response.setCharacterEncoding("utf-8");
	 * response.setContentType("multipart/form-data");
	 * response.setHeader("Content-Disposition", "attachment;fileName=" + new
	 * String(bean.getTitle())); OutputStream os = response.getOutputStream();
	 * byte[] b = new byte[2048]; int length; while((length = is.read(b)) > 0){
	 * os.write(b, 0, length); } os.close(); is.close(); } catch (IOException e)
	 * { logger.error("下载文件异常，异常原因为："+e.getMessage()); }
	 * 
	 * } } return null; }
	 */

	@Token(save = true)
	@RequestMapping("shelves")
	public String shelves(@RequestParam(value = "id", required = true) String id, Model model) {
		if (RegexUtils.isNumber(id)) {
			AxdInformationNotices bean = axdInformationNoticesService.findOneById(Integer.valueOf(id));
			bean.setNoticesId(Integer.valueOf(id));
			Integer count = 0;
			if (bean.getStates() == 1) {
				bean.setStates(0);
				count = axdInformationNoticesService.updateById(bean);
			} else {
				bean.setStates(1);
				count = axdInformationNoticesService.updateById(bean);
			}

			if (null == count || count <= 0) {
				logger.debug("上架信息设置失败");
				model.addAttribute("msg", "上架信息设置失败");
				model.addAttribute("redirect", "admin/informationNotices/index");
			}
		}
		model.addAttribute("msg", "上架信息设置成功");
		model.addAttribute("redirect", "admin/informationNotices/index");
		return "message";
	}

}
